package com.example.calendarapp;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Class for displaying month grid view
 * @author nathan
 *
 */


public class MonthFragment extends Fragment  {
	protected static String TAG = "MONTHACTIVITY";
	private static String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
	private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	public static Calendar c = Calendar.getInstance();
	private GestureDetector gestureDetector;
    private SimpleOnGestureListener listener;
    View.OnTouchListener gestureListener;
    private TextView t;
	private int numberOfColumns = 7;
	private int numberOfRows = 5;
	private GridView mGrid;
	private MonthViewAdapter adapter;
    boolean calculated = false;

	/**
	 * onCreate sets actionbar navigation to month
	 * 
	 * @param optionalArgs
	 */
	
    @Override
    public void onCreate(Bundle optionalArgs)
    {    	
    	adapter = new MonthViewAdapter(getActivity());
    	ActionBar actionBar = getActivity().getActionBar();
    	actionBar.setSelectedNavigationItem(0);
    	super.onCreate(optionalArgs);
    }
    
    
    /**
     * onCreateView sets up swipe detection adds grid view dynamically and sets adapter
     * sets griditemclick listener to open day fragment based on click
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return v
     */
    
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_month, container, false);


		final OtherSwipeDetector sd = new OtherSwipeDetector()
			{
				@Override
				public void left()
				{
					increment();
				}
				@Override
				public void right()
				{
					decrement();
				}
			};
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
		params.addRule(RelativeLayout.BELOW, R.id.monthtitle);
		params.addRule(RelativeLayout.ABOVE, R.id.butt);
		int oldId = 0;
		if(mGrid != null)
		{	
			Log.e("MF", "removing mGrid");
			calculated = false;
			oldId = mGrid.getId();
			((RelativeLayout)v.findViewById(R.id.rootview)).removeView(v.findViewById(mGrid.getId()));
		}
		mGrid = new GridView(getActivity()) {
				@Override 
				protected void onLayout(boolean changed, int l, int t, int r, int b) {
					super.onLayout(changed, l, t, r, b);
					if(!calculated)
						getDimens(); 
				} 
			}; 
		mGrid.setVerticalSpacing(0);
		mGrid.setHorizontalSpacing(0);
		mGrid.setStretchMode(GridView.NO_STRETCH);
		mGrid.setBackgroundColor(Color.rgb(100, 10, 10));
		mGrid.setOnTouchListener(sd);
		mGrid.setId(100);
		mGrid.setOnItemClickListener(new OnItemClickListener()
			{
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id)
				{
					if(!sd.swipeDetected())
					{
						int pos = (int) view.getTag();
						String dateString = adapter.getDateString(position);
						if(adapter.getDateString(position) != "")
						{
							FragmentManager fm = getFragmentManager();
							FragmentTransaction ft = fm.beginTransaction();
							DayFragment dayFrag = new DayFragment();
							Bundle bundle = new Bundle();
							bundle.putString("date", dateString);
							((Fragment)dayFrag).setArguments(bundle);
							ft.replace(R.id.frag, dayFrag);
							ft.addToBackStack(null);
							ft.commit();
						}	
					}
				}
	
			});
		((RelativeLayout)v.findViewById(R.id.rootview)).addView(mGrid, params);
        t = (TextView) v.findViewById(R.id.monthtitle);
        t.setText(months[c.get(Calendar.MONTH)]);
    	adapter.notifyDataSetChanged();
        return v;
    } 
	
	private int mCellWidth;
    private int mCellHeight;
    protected void getDimens() { 
        calculated = true;
        mCellWidth = mGrid.getWidth()/numberOfColumns;
        mCellHeight = mGrid.getHeight()/numberOfRows;
        mGrid.setColumnWidth(mCellWidth+1);
        mGrid.setNumColumns(numberOfColumns);
        adapter.setHeight(mGrid.getHeight());
        mGrid.setAdapter(adapter);
        adapter.notifyDataSetChanged();

    }
    
  /**
   * inrement the month and update the adapter and month string display
   */
    
    
    public void increment()
    {
		adapter.incrementMonth();
		c.add(Calendar.MONTH, 1);
		adapter.notifyDataSetChanged();
        t.setText(months[c.get(Calendar.MONTH)]);
    }
    
//    @Override
//    public void onDestroy()
//    {
//    	adapter.close();
//    	super.onDestroy();
//    }
//    
//    @Override
//    public void onResume()
//    {
//    	super.onResume();
//    }
//    
//    @Override
//    public void onSaveInstanceState(Bundle out)
//    {
//    	//nada
//    }
    
    /**
     * decrement the month and update the adapter and the month string display
     */
    
    public void decrement()
    {
		adapter.decrementMonth();
		adapter.notifyDataSetChanged();
		c.add(Calendar.MONTH, -1);
        t.setText(months[c.get(Calendar.MONTH)]);
    }
    
    

}
